import React from 'react';
import { Button, Input, Select } from 'antd'
const Option = Select.Option;
import baseService from 'share/base.service'
import debounce from 'lodash.debounce';
import isJSON from 'is-json';
import 'styles/components/location.scss'

class Location extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      value: { key: '', label: '' },
      options: []
    };
    this.search = debounce(this.search,500);
  }

  componentWillMount(){
    if(this.props.value)
      this.setValues(this.props.value);
  }

  setValues = propsValue => {
    try {
      let valueWillSet = {};
      if (isJSON(propsValue)) {
        valueWillSet = JSON.parse(propsValue);
      } else {
        valueWillSet = { address: propsValue, latitude: '', longitude: '' };
      }
      const { value } = this.state;
      if((value.data && value.key !== valueWillSet.address
          && value.data.location && value.data.location.lng !== valueWillSet.longitude) || !value.data){
        this.setState({
          value: {
            key: valueWillSet.address,
            label: valueWillSet.address,
            selectFlag: !!valueWillSet.longitude,
            data: {
              title: valueWillSet.address,
              location: {
                lng: valueWillSet.longitude,
                lat: valueWillSet.latitude
              }
            }
          }
        });
      }
    } catch(e) {
      console.log(e);
    }
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.value !== this.props.value) {
      this.setValues(nextProps.value);
    }
  }

  onChange = changedValue => {
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(changedValue);
    }
  };

  select = value => {
    const { options } = this.state;
    if(value && value.key && options){
      options.map(option => {
        option.address === value.key && this.setState({
          value: {
            key: option.title,
            label: option.title,
            selectFlag: true,
            data: option
          }
        }, () => {
          let result = {
            address: option.title,
            longitude: option.location.lng,
            latitude: option.location.lat
          };
          this.onChange(JSON.stringify(result));
        })
      })
    }
  };

  //ant3.8对mode='combobox'做了调整，所以换了种方案实现
  search = keyword => {
    if(!keyword) {
      this.setState({ options:[], value: {key: '', label: ''}}, () => {
        this.onChange(null);
      })
    }
    keyword && baseService.searchLocation(keyword).then(options => {
      this.setState({ value: {key: keyword, label: keyword, selectFlag: false }, options });
    });
  };

  blur = () => {
    let { value } = this.state;
    if (!(value && value.selectFlag) && value) {
      let result = {
        address: value.key,
        longitude: '',
        latitude: ''
      };
      this.onChange(JSON.stringify(result));
    }
  };

  render() {
    const { placeholder } = this.props;
    const { options, value } = this.state;
    return (
      <div className="location">
        <Select
          mode="combobox"
          showSearch
          labelInValue
          value={value}
          onSelect={this.select}
          onBlur={this.blur}
          onSearch={this.search}
          style={{ width: '100%' }}
          filterOption={false}
          defaultActiveFirstOption={false}
          disabled={this.props.disabled}
          getPopupContainer={triggerNode => triggerNode.parentNode}
          placeholder={placeholder}
        >
          {options.map(option => (
            <Option key={option.address}>
              <div>{option.title}</div>
              <div style={{ fontSize: 10, color: '' }}>{option.address}</div>
            </Option>
          ))}
        </Select>
      </div>
    );
  }
}

Location.PropTypes = {
  onChange: React.PropTypes.func,  //进行选择后的回调
  value: React.PropTypes.string,  //值
  placeholder: React.PropTypes.string,
  disabled: React.PropTypes.bool  //是否可编辑
};

Location.defaultProps = {
  disabled: false
};

Location.defaultProps = {};

export default Location;

